package com.example.spring.exercise.config;

import com.example.spring.exercise.security.UserTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;

/**
 * @author : zhayh
 * @date : 2021-4-18 16:07
 * @description : 权限配置类
 */

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Resource
    private UserTokenFilter userTokenFilter;
    @Resource
    private CorsFilter corsFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 指定密码加密模式：加盐哈希算法
        return new BCryptPasswordEncoder();
    }

    // 将登录模式设置为无状态模式，关闭跨站脚本攻击功能
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 设置无状态会话
                .and().csrf().disable() // 关闭跨域脚本攻击
                .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests() // 开放登录接口
                .antMatchers("/api/login").permitAll()
                .antMatchers("/api/admin/**").authenticated()
                .and()
                //将自定义过滤器添加到登录验证之前
                .addFilterBefore(userTokenFilter, UsernamePasswordAuthenticationFilter.class);;
    }
}
